<template>
  <div>
    <!--搜索框-->
    <el-form :inline="true" :model="searchForm">
      <el-form-item>
        <el-input v-model="searchForm.name" placeholder="期刊名称" clearable @clear="getList"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="select">搜索</el-button>
        <el-button type="primary" @click="saveHandle" v-if="hasAuth('periodical:manage:save')">新增</el-button>
      </el-form-item>
    </el-form>

    <!--列表-->
    <el-table border stripe :data="tableData" tooltip-effect="dark" style="width: 100%">
      <el-table-column prop="name" label="期刊名称"></el-table-column>
      <el-table-column prop="issn" label="ISBN码" width="150"></el-table-column>
      <el-table-column prop="totalIssue" label="总期数"></el-table-column>
      <el-table-column prop="typeName" label="类别"></el-table-column>
      <el-table-column prop="publisher" label="出版单位"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="editHandle(scope.row.id,true)">查看详情</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="text" @click="borrowHandle(scope.row.id)">借阅</el-button>
          <el-divider direction="vertical" v-if="hasAuth('periodical:manage:save')&&pagePerms.length>1"></el-divider>
          <el-button type="text" v-if="hasAuth('periodical:manage:save')" @click="saveIssueHandle(scope.row)">
            新增新期数
          </el-button>
          <el-divider direction="vertical" v-if="hasAuth('periodical:manage:save')&&pagePerms.length>1"></el-divider>
          <el-button type="text" v-if="hasAuth('periodical:manage:update')" @click="editIssueHandle(scope.row.id)">
            修改期数
          </el-button>
          <el-divider direction="vertical" v-if="hasAuth('periodical:manage:update')&&pagePerms.length>1"></el-divider>
          <el-button type="text" @click="editHandle(scope.row.id,false)" v-if="hasAuth('periodical:manage:update')">编辑
          </el-button>
          <el-divider direction="vertical" v-if="hasAuth('periodical:manage:delete')&&pagePerms.length>1"></el-divider>
          <el-popconfirm title="确定要删除这条记录吗？" @confirm="delHandle(scope.row.id,scope.row.issn)"
                         v-if="hasAuth('periodical:manage:delete')">
            <el-button type="text" slot="reference">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!--页码-->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="current"
                   :page-sizes="[10, 20, 50, 100]" :page-size="size" layout="total, sizes, prev, pager, next, jumper"
                   :total="total"></el-pagination>

    <el-dialog title="期刊信息" :visible.sync="dialogFormVisible" width="600px">
      <el-form :model="editForm" :rules="editFormRules" ref="editForm">
        <el-form-item label="期刊名称" prop="name" label-width="100px">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="ISSN码" prop="issn" label-width="100px">
          <el-input v-model="editForm.issn" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="中文名" prop="cname" label-width="100px">
          <el-input v-model="editForm.cname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="统一刊号" prop="unifyingCallNumber" label-width="100px">
          <el-input v-model="editForm.unifyingCallNumber" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="编辑部" prop="sponsors" label-width="100px">
          <el-input v-model="editForm.sponsors" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="出版单位" prop="publisher" label-width="100px">
          <el-input v-model="editForm.publisher" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="类别" prop="typeId" label-width="100px">
          <el-select v-model="editForm.typeId" filterable placeholder="请输入并选择期刊类别">
            <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.typeName"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="总期数" prop="totalIssue" label-width="100px">
          <el-input v-model="editForm.totalIssue" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="语种" prop="languages" label-width="100px">
          <el-input v-model="editForm.languages" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('editForm')">取 消</el-button>
        <el-button type="primary" @click="submitEditForm('editForm')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
        title="期数信息"
        :visible.sync="dialogVisible"
        width="45%">
      <p v-if="isBorrow" style="font-size: 20px">确定借阅该书籍吗？</p>

      <el-form :model="issueFormData" :rules="issueFormDataRules" ref="issueForm">
        <el-form-item label="期刊名称" prop="name" label-width="100px">
          <el-input readonly disabled v-model="issueFormData.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="ISSN码" prop="issn" label-width="100px">
          <el-input readonly disabled v-model="issueFormData.issn" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item v-if="!issueFormData.id" label="期数" prop="issue" label-width="100px">
          <el-input v-model="issueFormData.issue" autocomplete="off"></el-input>
          <el-alert :title="issueTitle" :closable="false" type="info"
                    style="line-height: 12px;"></el-alert>
        </el-form-item>
        <el-form-item v-if="isBorrow||issueFormData.id" label="期数" label-width="100px">
          <el-select @change="changeIssueHandle" v-model="issueIndex" filterable placeholder="请输入并选择期数">
            <el-option
                v-for="(item,index) in issueFormData.periodicalList"
                :key="item.issue"
                :label="item.issue"
                :value="index">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="!isBorrow&&!issueFormData.id" label="存入数量" prop="total" label-width="100px">
          <el-input type="number" v-model="issueFormData.total" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item v-if="issueFormData.id&&issueFormData.count" label="当前数量" prop="count" label-width="100px">
          <el-input :disabled="isBorrow" type="number" v-model="issueFormData.count" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item v-if="!isBorrow&&issueFormData.id&&issueFormData.total" label="总数量" prop="total"
                      label-width="100px">
          <el-input type="number" v-model="issueFormData.total" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item v-if="!isBorrow&&issueFormData.id&&issueFormData.brokenCount" label="破损数量" prop="brokenCount"
                      label-width="100px">
          <el-input type="number" v-model="issueFormData.brokenCount" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item v-if="!isBorrow&&!issueFormData.id" label="修改总期数" prop="updTotalIssue" label-width="100px">
          <el-switch
              v-model="issueFormData.updTotalIssue"
              active-text="修改"
              inactive-text="不修改">
          </el-switch>
          <el-alert title="默认为不修改总总数" :closable="false" type="info"
                    style="line-height: 12px;"></el-alert>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('issueForm')">取 消</el-button>
        <el-button v-if="!issueFormData.id||issueFormData.total" type="primary" @click="submitIssueForm('issueForm')">确
          定
        </el-button>
      </div>
    </el-dialog>

    <el-drawer
        :title="editForm.name"
        :visible.sync="drawer"
        @before-close="resetForm(editForm)">
      <p class="drawer-p" v-if="editForm.cname">
        <strong>中文名：</strong>
        <span>{{ editForm.cname }}</span>
      </p>
      <p class="drawer-p" v-if="editForm.isbn">
        <strong>ISSN码：</strong>
        <span>{{ editForm.issn }}</span>
      </p>
      <p class="drawer-p" v-if="editForm.unifyingCallNumber">
        <strong>统一刊号：</strong>
        <span>{{ editForm.unifyingCallNumber }}</span>
      </p>
      <p class="drawer-p" v-if="editForm.sponsors">
        <strong>编辑部：</strong>
        <span>{{ editForm.sponsors }}</span>
      </p>
      <p class="drawer-p" v-if="editForm.typeName">
        <strong>类别：</strong>
        <span>{{ editForm.typeName }}</span>
      </p>
      <p class="drawer-p" v-if="editForm.periodicalList">
        <strong>期数：</strong>
        <el-select v-model="issueIndex" @change="getIssue" filterable placeholder="请输入并选择期数">
          <el-option
              v-for="(item,index) in editForm.periodicalList"
              :key="item.id"
              :label="item.issue"
              :value="index">
          </el-option>
        </el-select>
      </p>
      <p class="drawer-p" v-if="editForm.languages">
        <strong>语种：</strong>
        <span>{{ editForm.languages }}</span>
      </p>
      <p class="drawer-p" v-if="editForm.count">
        <strong>当前数量：</strong>
        <span>{{ editForm.count }}</span>
      </p>
      <p class="drawer-p" v-if="editForm.total">
        <strong>总数量：</strong>
        <span>{{ editForm.total }}</span>
      </p>
      <p class="drawer-p" v-if="editForm.brokenCount">
        <strong>破损数量：</strong>
        <span>{{ editForm.brokenCount }}</span>
      </p>
    </el-drawer>
  </div>
</template>
<script>
import qs from "qs";

export default {
  name: "Periodical",
  data() {
    return {
      //搜索框表单
      searchForm: {name: null},
      //编辑表单
      editForm: {},
      updTotalIssue: false,
      issueIndex: null,
      issueTitle: null,
      //编辑表单规则
      editFormRules: {
        name: [{required: true, message: '请输入书籍名称', trigger: 'blur'}],
        issn: [{required: true, message: '请输入ISBN码', trigger: 'blur'}],
        publisher: [{required: true, message: '请输入出版单位', trigger: 'blur'}],
        unifyingCallNumber: [{required: true, message: '请输入统一刊号', trigger: 'blur'}],
        typeId: [{required: true, message: '请选择书籍类型', trigger: 'blur'}],
        totalIssue: [{required: true, message: '请输入总期数', trigger: 'blur'}],
        languages: [{required: true, message: '请输入书籍语种', trigger: 'blur'}],
      },
      issueFormDataRules: {
        name: [{required: true, message: '请输入书籍名称', trigger: 'blur'}],
        issn: [{required: true, message: '请输入ISSN码', trigger: 'blur'}],
        issue: [{required: true, message: '期数不能为空', trigger: 'blur'}],
        count: [{required: true, message: '请输入期刊的当前数量', trigger: 'blur'}],
        total: [{required: true, message: '请输入期刊数量', trigger: 'blur'}],
      },
      //当前页，默认为1
      current: 1,
      //记录总数，默认为0
      total: 0,
      //每页记录数，默认每页10条
      size: 10,
      //是否显示编辑/新增dialog
      dialogFormVisible: false,
      //表格数据
      tableData: [],
      //当前页需要的权限列表，只包括按钮类型
      pagePerms: [],
      //是否选择记录，如果否则禁用批量删除按钮
      delBtnStu: true,
      //是否显示抽屉
      drawer: false,
      options: [],
      dialogVisible: false,
      issueFormData: {},
      isBorrow: false

    }
  },
  methods: {
    borrowHandle(id) {
      this.dialogVisible = true
      this.isBorrow = true;
      this.editIssueHandle(id);
    },
    select() {
      this.current = 1;
      this.getList();
    },
    saveHandle() {
      this.resetForm('editForm');
      this.$axios.get('/type/list').then(res => {
        this.options = res.data.data;
      });
      this.dialogFormVisible = true
    },
    saveIssueHandle(row) {
      this.resetForm('issueForm');
      this.issueFormData.issn = row.issn;
      this.issueFormData.name = row.name;
      this.issueTitle = "请仿照已存在的期数进行添加，例如：" + row.totalIssue;
      this.dialogVisible = true;
    },
    getList() {
      this.$axios.get('/periodical', {
        params: {
          name: this.searchForm.name,
          current: this.current,
          size: this.size
        }
      }).then(res => {
        this.tableData = res.data.data
        this.total = res.data.total
      })
    },
    getIssue() {
      let periodical = this.editForm.periodicalList[this.issueIndex];
      this.editForm.count = periodical.count;
      this.editForm.total = periodical.total;
      this.editForm.brokenCount = periodical.brokenCount;
    },
    handleSizeChange(val) {
      this.size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.current = val
      this.getList()
    },
    submitIssueForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: 'loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          if (!this.isBorrow) {
            this.$axios({
              method: this.issueFormData.id ? 'put' : 'post',
              url: '/periodical/issue',
              data: this.issueFormData
            }).then(res => {
              loading.close();
              this.resetForm(formName)
              this.$message({
                showClose: true, message: '恭喜你，操作成功', type: 'success', duration: 2000, onClose: () => {
                  this.getList()
                }
              });
            })
          } else {
            this.$axios.post("/borrowRecord/userBorrow", {
              bookId: this.issueFormData.id,
              bookPeriodical: 1,
            }).then((res) => {
              loading.close();
              this.resetForm(formName)
              this.$message({
                showClose: true, message: '恭喜你，借阅成功', type: 'success', duration: 2000, onClose: () => {
                  this.getList()
                }
              });
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    submitEditForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: 'loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          this.$axios({
            method: this.editForm.id ? 'put' : 'post',
            url: '/periodical',
            data: this.editForm
          }).then(res => {
            loading.close();
            this.resetForm(formName)
            this.$message({
              showClose: true, message: '恭喜你，操作成功', type: 'success', duration: 2000, onClose: () => {
                this.getList()
              }
            });
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    editHandle(id, isDrawer) {
      const loading = this.$loading({
        lock: true,
        text: 'loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.resetForm('editForm');
      this.$axios.get('/type/list').then(res => {
        this.options = res.data.data;
      });
      this.$axios.get("/periodical/info/" + id).then(res => {
        loading.close();
        this.editForm = res.data.data
        if (isDrawer) {
          this.drawer = true;
        } else {
          this.dialogFormVisible = true
        }
      })
    },
    changeIssueHandle() {
      let periodical = this.issueFormData.periodicalList[this.issueIndex];
      this.issueFormData.count = periodical.count;
      this.issueFormData.total = periodical.total;
      this.issueFormData.brokenCount = periodical.brokenCount;

    },
    editIssueHandle(id) {
      const loading = this.$loading({
        lock: true,
        text: 'loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.resetForm('issueUpdForm');
      this.$axios.get("/periodical/info/" + id).then(res => {
        loading.close();
        this.issueFormData = res.data.data
        this.dialogVisible = true
      })

    },
    delHandle(id, issn) {
      this.$axios.delete("/periodical/" + id, {
        params: {
          issn: issn,
        },
        paramsSerializer: params => {
          return qs.stringify(params, {indices: false})
        }
      }).then(res => {
        this.$message({
          showClose: true, message: '恭喜你，操作成功', type: 'success', duration: 2000, onClose: () => {
            this.getList()
          }
        });
      })
    },
    resetForm(formName) {
      this.dialogFormVisible = false;
      this.dialogVisible = false;
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
      this.issueIndex = null;
      this.issueFormData = {};
      this.editForm = {};
    },
  },
  created() {
    this.getList();
    this.pagePerms = this.getPagePerms(this.$route.name);
  }
}
</script>

<style scoped>
.el-pagination {
  float: right;
  margin-top: 20px;
  padding-bottom: 30px;
}

.drawer-p {
  margin-left: 20px;
}
</style>
